var areaData = address;
var $form;
var form;
var upload;
var laydate;
var $;
layui.config({
	base : "/js/"
}).use(['form','layer','upload','laydate'],function() {
    form = layui.form;

    var layer = parent.layer === undefined ? layui.layer : parent.layer;
    $ = layui.jquery;
    $form = $('form');
    upload = layui.upload;
    laydate = layui.laydate;
    loadProvince(); //加载省信息
    upload.render({
        elem: '#userFaceBtn',
        url: '/file/upload/',
        field: 'test',
        before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#userFace').attr('src', result); //图片链接（base64）
            });
            layer.load(2, {
                shade: [0.3, '#333']
            });
        },
        done: function (res, index, upload) {
            layer.closeAll('loading');
            //如果上传失败
            if (res.success === false) {
                return layer.msg('上传失败');
            } else {
                layer.msg("上传成功", {time: 1000}, function () {
                    $("input[name='image']").val(res.data.url);
                })
            }
        }
    });
    laydate.render({
        elem: '#birthday', //指定元素
    });
    //添加验证规则
    form.verify({
        // oldPwd: function (value, item) {
        //     if (value != "123456") {
        //         return "密码错误，请重新输入！";
        //     }
        // },
        newPwd: function (value, item) {
            if (value.length < 6) {
                return "密码长度不能小于6位";
            }
        },
        confirmPwd: function (value, item) {
            if (!new RegExp($("#oldPwd").val()).test(value)) {
                return "两次输入密码不一致，请重新输入！";
            }
        }
    })

    //判断是否修改过用户信息，如果修改过则填充修改后的信息
    if (window.sessionStorage.getItem('userInfo')) {
        var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
        var citys;
        $(".realName").val(userInfo.realName); //用户名
        $(".userSex input[value=" + userInfo.sex + "]").attr("checked", "checked"); //性别
        $(".userPhone").val(userInfo.userPhone); //手机号
        $(".userBirthday").val(userInfo.userBirthday); //出生年月
        $(".userAddress select[name='province']").val(userInfo.province); //省
        //填充省份信息，同时调取市级信息列表
        var value = userInfo.province;
        var d = value.split('_');
        var code = d[0];
        var count = d[1];
        var index = d[2];
        if (count > 0) {
            loadCity(areaData[index].mallCityList);
            citys = areaData[index].mallCityList
        } else {
            $form.find('select[name=city]').attr("disabled", "disabled");
        }
        $(".userAddress select[name='city']").val(userInfo.city); //市
        //填充市级信息，同时调取区县信息列表
        var value = userInfo.city;
        var d = value.split('_');
        var code = d[0];
        var count = d[1];
        var index = d[2];
        if (count > 0) {
            loadArea(citys[index].mallAreaList);
        } else {
            $form.find('select[name=area]').attr("disabled", "disabled");
        }
        $(".userAddress select[name='area']").val(userInfo.area); //区
        for (key in userInfo) {
            if (key.indexOf("like") != -1) {
                $(".userHobby input[name='" + key + "']").attr("checked", "checked");
            }
        }
        $(".userEmail").val(userInfo.userEmail); //用户邮箱
        $(".myself").val(userInfo.myself); //自我评价
        form.render();
    }
    //
    // //判断是否修改过头像，如果修改过则显示修改后的头像，否则显示默认头像
    // if(window.sessionStorage.getItem('userFace')){
    // 	$("#userFace").attr("src",window.sessionStorage.getItem('userFace'));
    // }else{
    // 	$("#userFace").attr("src","/img/face.jpg");
    // }

    //提交个人资料
    form.on("submit(changeUser)", function (data) {
        var index = layer.msg('提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        //将填写的用户信息存到session以便下次调取
        var key, userInfoHtml = '';
        userInfoHtml = {
            'realName': data.field.realName,
            'sex': data.field.sex,
            'age': data.field.age,
            'birthday': data.field.birthday,
            'province': data.field.province,
            'city': data.field.city,
            'area': data.field.area,
            'email': data.field.email,
            'image': data.field.image,
            'myself': $(".myself").val()
        };
        for (key in data.field) {
            if (key.indexOf("like") != -1) {
                userInfoHtml[key] = "on";
            }
        }
        window.sessionStorage.setItem("userInfo", JSON.stringify(userInfoHtml));
        setTimeout(function () {
            layer.close(index);
            layer.msg("提交成功！");
        }, 2000);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    })

    form.on("submit(changeUser)", function (data) {
        if (data.field.id == null) {
            layer.msg("用户ID不存在");
            return false;
        }
        var loadIndex = layer.load(2, {
            shade: [0.3, '#333']
        });
        $.post("saveUserInfo", data.field, function (res) {
            layer.close(loadIndex);
            if (res.success) {
                parent.layer.msg("您的个人信息保存成功！", {time: 1500}, function () {
                    parent.location.reload();
                });
            } else {
                layer.msg(res.message);
            }
        });
        return false;
    });

    $(".restuserinfo").on("click", function () {
        layer.confirm('确定重置个人信息么?', {icon: 3, title: '提示'}, function (index) {
            window.location.reload();
            layer.close(index);
        });
    });

    form.on("submit(changePwd)", function (data) {
        $.post("changePassword", data.field, function (res) {
            if (res.success) {
                layer.msg("密码修改成功,请重新登录", {"time": 1000}, function () {
                    sessionStorage.clear();
                    localStorage.clear();
                    parent.location.href = "logout";
                })
            } else {
                layer.msg(res.message);
            }
        });
        return false;
    });

//加载省数据
    function loadProvince() {
        var proHtml = '';
        for (var i = 0; i < areaData.length; i++) {
            proHtml += '<option value="' + areaData[i].provinceCode + '_' + areaData[i].mallCityList.length + '_' + i + '">' + areaData[i].provinceName + '</option>';
        }
        //初始化省数据
        $form.find('select[name=province]').append(proHtml);
        form.render();
        form.on('select(province)', function (data) {
            $form.find('select[name=area]').html('<option value="">请选择县/区</option>');
            var value = data.value;
            var d = value.split('_');
            var code = d[0];
            var count = d[1];
            var index = d[2];
            if (count > 0) {
                loadCity(areaData[index].mallCityList);
            } else {
                $form.find('select[name=city]').attr("disabled", "disabled");
            }
        });
    }

//加载市数据
    function loadCity(citys) {
        var cityHtml = '<option value="">请选择市</option>';
        for (var i = 0; i < citys.length; i++) {
            cityHtml += '<option value="' + citys[i].cityCode + '_' + citys[i].mallAreaList.length + '_' + i + '">' + citys[i].cityName + '</option>';
        }
        $form.find('select[name=city]').html(cityHtml).removeAttr("disabled");
        form.render();
        form.on('select(city)', function (data) {
            var value = data.value;
            var d = value.split('_');
            var code = d[0];
            var count = d[1];
            var index = d[2];
            if (count > 0) {
                loadArea(citys[index].mallAreaList);
            } else {
                $form.find('select[name=area]').attr("disabled", "disabled");
            }
        });
    }

//加载县/区数据
    function loadArea(areas) {
        var areaHtml = '<option value="">请选择县/区</option>';
        for (var i = 0; i < areas.length; i++) {
            areaHtml += '<option value="' + areas[i].areaCode + '">' + areas[i].areaName + '</option>';
        }
        $form.find('select[name=area]').html(areaHtml).removeAttr("disabled");
        form.render();
        form.on('select(area)', function (data) {
        });
    }
})
